/**
 * Created by songjuxi on 2017/3/29.
 */
import React from 'react'
import { Modal, Col, Input, Form, Button, Select, Upload, Message } from 'jdcloudui';
import './style/style.css'
const FormItem = Form.Item;
const Option = Select.Option
const imgTypes = ['application/x-jpg', 'image/jpeg', 'image/png', 'application/x-png', 'application/x-bmp', 'image/bmp']
@Form.create()
export default class BuyerBillOperate extends React.Component {
  constructor(props) {
    super(props)
    this.state = { loading: false, disabled: false, fileList: [], uploadDisabled: false }
    props.form.getFieldDecorator('invoiceImgSrcName');
  }
  handleOk() {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.id = parseInt(this.props.linkdata.id)
        console.log('Received values of form: ', values);
        this.setState({ loading: true, disabled: true })
        this.props.buyerBillOperate(values)
          .then((result) => {
            this.setState({ loading: false, disabled: false })
            this.props.form.resetFields();
            this.props.showModal(false);
            this.setState({ fileList: [] });
            this.props.form.setFieldsValue({
              logisticsNo: null,
              logisticsCompany: null
            })
            let searchdata = this.props.searchdata
            searchdata.pageNum = searchdata.pageNum || 1
            searchdata.pageSize = searchdata.pageSize || 10
            this.props.buyerBillSearch(searchdata);
          }, (error) => {
            console.log('SearchData fail')
          }
          ).catch((e) => {
            console.log(e)
          })
      }
    });
  }
  handleCancel(e) {
    this.props.form.resetFields()
    this.setState({ fileList: [] })
    this.props.showModal(false);
  }
  onChange({ file, fileList, e }) {
    console.log(file, fileList, 'xxxxx')
    if (imgTypes.indexOf(file.type) < 0) {
      Message.warning('只能是jpg、jpeg、png、bmp中的一种')
      return;
    }
    const lasDot = file.name.lastIndexOf('.')
    const name = file.name.substring(0, lasDot)
    if (name.length > 20) {
      Message.warning('文件名长度不能大于20')
      return;
    }
    if (file.status === 'done') {
      this.setState({ uploadDisabled: false })
      if (file.response.code == 0) {
        this.setState({ fileList: [file] })
        this.props.form.setFieldsValue({ invoiceImgSrcName: file.name })
        Message.success(file.response.msg)
      } else {
        this.setState({ fileList: fileList.length >= 2 ? [fileList[0]] : [] })
        Message.warning(file.response.msg)
      }
    } else if (file.status === 'removed') {
      this.setState({ fileList, uploadDisabled: false })
      console.log(fileList, 'filelist')
      if (fileList.length == 0) {
        this.props.form.resetFields(['invoiceImgSrcName', 'invoiceImgSrc'])
      }

    } else {
      this.setState({ fileList, uploadDisabled: true })
    }
  }

  render() {
    const { getFieldDecorator, getFieldValue, resetFields } = this.props.form;
    let linkdata = this.props.linkdata || {};
    return (
      <div >
        <Modal
          mashClosable={false}
          title="确认开票"
          visible={this.props.visible}
          onCancel={this.handleCancel.bind(this)}
          maskClosable={false}
          className="invoice-buyer-modal"

          footer={[
            <Button
              key="back"
              size="large"
              disabled={this.state.disabled}
              onClick={this.handleCancel.bind(this)}>
              取消</Button>,
            <Button
              key="submit"
              type="primary"
              size="large"
              loading={this.state.loading}
              onClick={this.handleOk.bind(this)}>
              确定
            </Button>,
          ]}
        >
          <Col className="pb10" >
            <span className="f-ib widHalf" >联系人：{linkdata.linkMan}</span>
            <span className="f-ib widHalf" >联系方式：{linkdata.linkPhone}</span>
          </Col>
          <Col style={{ marginBottom: 10 }}>地址：{linkdata.linkAddress}</Col>
          <Form layout="inline" >
            <FormItem label="发票代码">
              {getFieldDecorator('invoiceCode', {
                rules: [{ required: true, message: '请输入发票代码', whitespace: true }, {
                  pattern: /^\d{10,12}$/, message: '请输入正确发票代码'
                }]
              })(<Input maxLength={20} />)}
            </FormItem>
            <FormItem label="发票号码">
              {getFieldDecorator('invoiceNum', {
                rules: [{ required: true, message: '请输入发票号码', whitespace: true }, {
                  message: '发票号码是8位字母或数字', pattern: /^[a-zA-Z\d]{8}$/
                }]
              })(<Input maxLength={20} />)}
            </FormItem>
              <FormItem label="发票照片" className="invoice-photo">
                {getFieldDecorator('invoiceImgSrc', {
                  rules: [{ required: true, message: '请上传发票照片', whitespace: true }],
                  getValueFromEvent: ({ fileList = [] }) => {
                    return fileList[0] && fileList[0].response && fileList[0].response.data
                  },
                })(
                  <Upload
                    action="/proxy/base/upload//uploadImgLimitFiveMega"
                    onChange={::this.onChange}
                    fileList={this.state.fileList}
                  >
                    <Button disabled={this.state.uploadDisabled}>
                    {this.state.fileList.length ? '重新上传' : '上传'}
                  </Button>
                  （仅支持jpg、jpeg、png、bmp格式，限5M以内）
                  </Upload>
                )}
              </FormItem>
            <FormItem label="物流公司" >
              {getFieldDecorator('logisticsCompany', {
                rules: [{ required: true, message: '请输入物流公司', whitespace: true }]
              }
              )(
                <Input maxLength={20} />
              )}
            </FormItem>
            <FormItem label="物流单号">
              {getFieldDecorator('logisticsNo', {
                rules: [{ required: true, message: '请输入物流单号', whitespace: true }],
              }
              )(
                <Input maxLength={20} />
              )}
            </FormItem>
          </Form>
        </Modal>
      </div >
    )
  }
}